import type { CacheOperate, MenuState } from './types/menu'
import { constantMenus } from '@/router'
import { ascending, filterNoPermissionTree, filterTree } from '@/router/utils'
import { store } from '@/stores'
import { defineStore } from 'pinia'
import { useTagsViewStoreHook } from './tagsView'

export const useMenuStore = defineStore(`${import.meta.env.VITE_NAMESPACE}-menus`, {
  state: (): MenuState => ({
    constantMenus,
    menus: [],
    cachePageList: [],
  }),
  actions: {
    /**
     * 组装菜单
     * @param routes
     */
    handleMenus(routes: any) {
      this.menus = filterNoPermissionTree(filterTree(ascending(this.constantMenus.concat(routes))))
    },
    /**
     * 缓存页面
     */
    cacheOperate({ type, name }: CacheOperate) {
      const delIndex = this.cachePageList.findIndex(v => v === name)
      switch (type) {
        case 'refresh':
          this.cachePageList = this.cachePageList.filter(v => v !== name)
          break
        case 'add':
          if (this.cachePageList.findIndex(v => v === name) === -1) {
            this.cachePageList.push(name)
          }
          break
        case 'delete':
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1)
          break
      }
      /** 监听缓存页面是否存在于标签页，不存在则删除 */
      useDebounceFn(() => {
        const cacheLength = this.cachePageList.length
        const tagViewList = useTagsViewStoreHook().tagsViewList
        for (let i = cacheLength - 1; i >= 0; i--) {
          const pageName = this.cachePageList[i]
          if (tagViewList.findIndex(v => v.name === pageName) === -1) {
            // 在这里不需要再使用 indexOf 查找索引，因为我们已经有了确切的索引 i
            this.cachePageList.splice(i, 1)
          }
        }
      })()
    },
    /**
     * 重置状态
     */
    resetState() {
      this.menus = []
      this.cachePageList = []
    },
  },
})

export function useMenuStoreHook() {
  return useMenuStore(store)
}
